
PLUGIN_PATH = File.join(RAILS_ROOT, 'vendor', 'plugins')

require File.join(PLUGIN_PATH,'jsrake', 'lib', 'jsrake.rb')
require File.join(PLUGIN_PATH,'rbnarcissus', 'init.rb')

OUTPUT_FILENAME = File.join(RAILS_ROOT, 'public/javascripts/compiled.js')

include JSRake

# JS Validator

namespace :js do
  
  desc 'Compile the javascript.'
  task :build do

    # Load Files

    javascript_base = File.join(RAILS_ROOT, "app", "javascripts" )
    js_glob_pattern = File.join("**", "*.js")
    
    script_files = PatternFileList.new(javascript_base, js_glob_pattern)
    sorted_script_files = TopoSortedFileList.new(script_files)
    
    # Concatenate
    concatenator = JSFileConcatenator.new(sorted_script_files)
    
    File.open(OUTPUT_FILENAME, "w") do |out_f|  
      concatenator.write_to out_f
    end
    
    # Validate output
    File.open OUTPUT_FILENAME do |file|
      begin
        data = StringIO.new
        concatenator.write_to data
        RbNarcissus::Matcher.new data.read
        puts "Compiled script verified."        
      rescue RbNarcissus::JavascriptParser::SyntaxError => e
        puts "#{OUTPUT_FILENAME}: #{e.message}"
      end
    end
        
  end
  
  desc "Validate the javascript"
  task :validate do
    
    # Load Files

    javascript_base = File.join( "app", "javascripts" )
    js_glob_pattern = File.join("**", "*.js")
    
    script_files = PatternFileList.new(javascript_base, js_glob_pattern)
    
    # Validate
    
    script_files.each_pair do |filename, file|
      
      begin
        RbNarcissus::Matcher.new file.read
        puts "#{filename}: No errors"
      rescue RbNarcissus::JavascriptParser::SyntaxError => e
        puts "#{filename}: #{e.message}"
      end
      
    end
  
  end
  
end